package com.happy.unitconvert.config;

import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * Redis配置类
 * 配置Redis连接和操作模板
 *
 * @author Happy
 */
@Configuration
@RequiredArgsConstructor
@ConditionalOnProperty(name = "app.exchange-rate.cache-enabled", havingValue = "true", matchIfMissing = true)
public class RedisConfig {

  /**
   * 配置反应式Redis模板
   * 使用String序列化器进行键值序列化
   */
  @Bean
  public ReactiveRedisTemplate<String, String> reactiveRedisTemplate(
      ReactiveRedisConnectionFactory connectionFactory) {

    StringRedisSerializer stringSerializer = new StringRedisSerializer();

    RedisSerializationContext<String, String> serializationContext = RedisSerializationContext
        .<String, String>newSerializationContext()
        .key(stringSerializer)
        .value(stringSerializer)
        .hashKey(stringSerializer)
        .hashValue(stringSerializer)
        .build();

    ReactiveRedisTemplate<String, String> template = new ReactiveRedisTemplate<>(connectionFactory,
        serializationContext);

    return template;
  }
}
